<template>
  <div class="recommend-products-section">
    <div class="section-header">
      <div class="header-grid">
        <h2 class="title">
          <span class="title-text">推荐商品</span>
          <span class="subtitle">精选好物</span>
        </h2>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载推荐商品...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>加载失败，请重试</p>
      <button @click="loadRecommendGoods" class="retry-button">重新加载</button>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!products.length" class="empty-container">
      <p>暂无推荐商品</p>
    </div>

    <!-- 滚动加载提示 -->
    <div v-if="scrollLoading" class="scroll-loading">
      <div class="loading-spinner small"></div>
    </div>

    <div v-else class="products-container">
      <div
        v-for="(product, index) in products"
        :key="product.goods_id || index"
        :class="['product-card', { 'last-item': index === products.length - 1 }]"
        @click="goToProductDetail(product.goods_id)"
      >
        <!-- 秒杀标签 - 优先显示 -->
        <div v-if="product.is_flash_sale" class="flash-sale-tag">
          <span class="badge-text">秒杀</span>
        </div>

        <div class="product-image">
          <img
            v-if="product.goods_cover_img"
            v-lazy="product.goods_cover_img"
            :alt="product.goods_name"
            class="product-img"
            @error="handleImageError"
          />
          <div v-else class="image-placeholder" :style="{ backgroundColor: product.bgColor }">
            <span class="placeholder-text">暂无图片</span>
          </div>
        </div>

        <div class="product-info">
          <h3 class="product-name">{{ product.goods_name }}</h3>
          <!-- 移除评分部分 -->
          <div class="price-section">
            <span class="current-price">¥{{ product.goods_price }}</span>
            <span
              class="original-price"
              v-if="
                product.market_price &&
                parseFloat(product.market_price) > parseFloat(product.goods_price)
              "
            >
              ¥{{ product.market_price }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { goodsApi, type GoodsBase } from '@/api/goods'

interface Product extends GoodsBase {
  bgColor?: string
}

const products = ref<Product[]>([])
const loading = ref(false)
const error = ref(false)

// 随机颜色生成
const colors = [
  '#FFECB3',
  '#FFCCBC',
  '#FFF9C4',
  '#C8E6C9',
  '#B3E5FC',
  '#E1BEE7',
  '#F8BBD0',
  '#DCEDC8',
  '#FFE0B2',
  '#E0F7FA',
]
const router = useRouter()

// 滚动加载状态
const scrollLoading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 10

// Intersection Observer 用于懒加载
let observer: IntersectionObserver | null = null
const observeLastItem = () => {
  if (observer) {
    observer.disconnect()
  }

  const items = document.querySelectorAll('.product-card')
  if (items.length === 0) return

  const lastItem = items[items.length - 1]
  observer = new IntersectionObserver(
    async ([entry]) => {
      if (entry.isIntersecting && hasMore.value && !scrollLoading.value) {
        console.log('检测到滚动到底部，开始加载更多推荐商品...')
        await loadMoreProducts()
      }
    },
    {
      rootMargin: '200px',
      threshold: 0.1,
    },
  )

  observer.observe(lastItem)
  console.log('已设置观察器监控最后一个推荐商品元素')
}

// 加载更多商品
const loadMoreProducts = async () => {
  if (scrollLoading.value || !hasMore.value) return

  scrollLoading.value = true
  currentPage.value++

  try {
    const response = await goodsApi.getRecommendGoods({
      type: 'rating',
      limit: pageSize,
      offset: (currentPage.value - 1) * pageSize,
    })

    console.log('加载更多推荐商品API响应:', response)
    // 打印新加载的数据
    console.group('新加载的推荐商品数据')
    console.table(
      response.results.map((p) => ({
        id: p.goods_id,
        name: p.goods_name,
        price: p.goods_price,
      })),
    )
    console.groupEnd()

    if (response && Array.isArray(response.results)) {
      const newProducts = response.results.map((product) => ({
        ...product,
        bgColor: getRandomColor(),
      }))

      products.value = [...products.value, ...newProducts]
      hasMore.value = newProducts.length === pageSize

      // 延迟观察新项目，确保DOM已更新
      setTimeout(observeLastItem, 100)
    } else {
      hasMore.value = false
    }
  } catch (error) {
    console.error('加载更多商品失败:', error)
    hasMore.value = false
  } finally {
    scrollLoading.value = false
  }
}
const getRandomColor = (): string => {
  return colors[Math.floor(Math.random() * colors.length)]
}

// 图片加载失败处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
  const placeholder = document.createElement('div')
  placeholder.className = 'image-placeholder'
  placeholder.style.backgroundColor = getRandomColor()
  placeholder.innerHTML = '<span class="placeholder-text">图片加载失败</span>'
  img.parentNode?.insertBefore(placeholder, img.nextSibling)
}

// 监听products变化重新设置观察器
watch(products, () => {
  nextTick(() => {
    observeLastItem()
  })
})

// 加载推荐商品
const loadRecommendGoods = async () => {
  loading.value = true
  error.value = false

  try {
    console.log('开始调用推荐商品API...')
    // 调用推荐商品接口
    const response = await goodsApi.getRecommendGoods({
      type: 'rating',
      limit: 5,
    })

    console.log('推荐商品API响应:', response)
    console.log('响应数据类型:', typeof response)
    console.log('响应结果:', response.results)
    console.log('结果是否为数组:', Array.isArray(response.results))
    console.log('结果长度:', response.results?.length)

    if (response && Array.isArray(response.results)) {
      console.log('处理推荐商品数据...')
      products.value = response.results.map((product) => ({
        ...product,
        bgColor: getRandomColor(),
        // 移除 goods_rating 赋值
      }))
      console.log('处理后的商品数据:', products.value)
    } else {
      console.error('推荐商品API响应结构异常:', response)
      throw new Error('API返回的数据结构不符合预期')
    }
  } catch (err) {
    console.error('加载推荐商品失败:', err)
    error.value = true
  } finally {
    loading.value = false
    console.log('加载完成，loading状态:', loading.value)
  }
}

const goToProductDetail = (productId: number) => {
  router.push(`/product/${productId}`)
}

// 组件挂载时加载数据
onMounted(() => {
  loadRecommendGoods().then(() => {
    // 初始加载完成后设置观察器
    observeLastItem()
  })
})

// 组件卸载时清理观察器
onUnmounted(() => {
  if (observer) {
    observer.disconnect()
  }
})
</script>

<style scoped lang="scss">
.recommend-products-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 30px;

  .section-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;

    .header-grid {
      display: grid;
      grid-template-columns: 1fr auto;
      align-items: end;
      gap: 20px;

      .title {
        display: flex;
        align-items: baseline;
        gap: 15px;
        min-width: 0;

        .title-text {
          font-size: 22px;
          font-weight: 700;
          color: #333;
          position: relative;
          white-space: nowrap;

          &::after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 100%;
            height: 3px;
            background: linear-gradient(to right, #ff6b6b, #ff8e53);
          }
        }

        .subtitle {
          font-size: 16px;
          color: #666;
          white-space: nowrap;
        }
      }

      .view-more {
        color: #666;
        font-size: 14px;
        text-decoration: none;
        display: flex;
        align-items: center;
        white-space: nowrap;

        &::after {
          content: '→';
          margin-left: 5px;
          transition: transform 0.2s;
        }

        &:hover {
          color: #ff6b6b;

          &::after {
            transform: translateX(3px);
          }
        }
      }
    }
  }

  // 加载状态样式
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;

    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid #f3f3f3;
      border-top: 3px solid #ff6b6b;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 16px;
    }

    p {
      color: #666;
      font-size: 14px;
    }
  }

  // 错误状态样式
  .error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;

    p {
      color: #ff4e50;
      font-size: 14px;
      margin-bottom: 16px;
    }

    .retry-button {
      padding: 8px 16px;
      background: #ff6b6b;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        background: #ff5252;
      }
    }
  }

  // 滚动加载状态
  .scroll-loading {
    grid-column: 1 / -1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 0;

    .loading-spinner.small {
      width: 24px;
      height: 24px;
      border-width: 2px;
      margin-bottom: 12px;
    }

    p {
      color: #666;
      font-size: 14px;
    }
  }

  // 没有更多数据
  .no-more-data {
    grid-column: 1 / -1;
    text-align: center;
    padding: 30px 0;
    color: #999;
    font-size: 14px;
  }

  // 空状态样式
  .empty-container {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 60px 0;

    p {
      color: #999;
      font-size: 16px;
    }
  }

  .products-container {
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr));
    gap: 16px;
    padding: 0 20px;

    .product-card {
      position: relative;
      background: #ffffff;
      border: 1px solid #f0f0f0;
      border-radius: 12px;
      transition: all 0.3s ease;
      overflow: hidden;
      padding: 16px;
      display: flex;
      flex-direction: column;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      cursor: pointer;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
      }
    }

    .product-badge {
      position: absolute;
      top: 10px;
      right: 10px;
      padding: 3px 8px;
      background: linear-gradient(to right, #ff6b6b, #ff8e53);
      color: white;
      font-size: 12px;
      border-radius: 3px;
      z-index: 5;
    }

    .flash-sale-tag {
      position: absolute;
      top: 10px;
      left: 10px;
      background: linear-gradient(135deg, #ff4e50, #f9002f);
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      z-index: 10; /* 确保秒杀标签在最上层 */
      box-shadow: 0 2px 8px rgba(255, 0, 0, 0.3);
    }

    .product-image {
      border-radius: 6px;
      overflow: hidden;
      margin-bottom: 12px;
      height: 160px;
      display: flex;
      align-items: center;
      justify-content: center;

      .product-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.05);
        }
      }

      .image-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: transform 0.3s ease;

        .placeholder-text {
          color: #999;
          font-size: 14px;
        }
      }
    }

    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      .product-name {
        font-size: 15px;
        font-weight: 600;
        margin-bottom: 10px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        min-height: 44px;
        line-height: 1.4;
      }

      .rating-section {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        gap: 6px;

        .stars {
          color: #ffc107;
          font-size: 12px;
        }

        .rating-score {
          font-size: 12px;
          color: #ff6b6b;
          font-weight: 600;
        }
      }

      .price-section {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-top: auto;

        .current-price {
          font-size: 16px;
          font-weight: 700;
          color: #ff4e50;
        }

        .original-price {
          font-size: 12px;
          color: #999;
          text-decoration: line-through;
        }
      }
    }
  }

  @media (max-width: 1200px) {
    .products-container {
      grid-template-columns: repeat(4, minmax(0, 1fr));
    }
  }

  @media (max-width: 768px) {
    .products-container {
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 12px;
      padding: 0 15px;
    }
  }

  @media (max-width: 480px) {
    .products-container {
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 10px;
      padding: 0 10px;
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
